package flyweight.main.factory;

import flyweight.main.object.AbstractChessman;
import flyweight.main.object.BlackChessman;
import flyweight.main.object.WhiteChessman;

import java.util.Hashtable;

public class FiveChessmanFactory {
    //单例模式工厂
    private static FiveChessmanFactory fiveChessmanFactory = new FiveChessmanFactory();
    //缓存存放共享对象
    private final Hashtable<Character, AbstractChessman> cache = new Hashtable<>();

    public FiveChessmanFactory() {
    }

    public static FiveChessmanFactory getInstance() {
        return fiveChessmanFactory;
    }

    /**
     *
     */
    public AbstractChessman getChessmanObject(char c) {
        //从缓存中获取棋子对象实例
        AbstractChessman abstractChessman = this.cache.get(c);
        if (null == abstractChessman) {
            switch (c) {
                case 'B':
                    abstractChessman = new BlackChessman();
                    break;
                case 'W':
                    abstractChessman = new WhiteChessman();
                    break;
                default:
                    break;
            }
            //防止非法字符进入，返回null
            if (abstractChessman != null) {
                //放入缓存
                this.cache.put(c, abstractChessman);
            }
        }
        //如果缓存中存在棋子对象则直接返回
        return abstractChessman;
    }

}
